﻿using System.IO;
using Ionic.Zlib;

namespace FlashToolKit
{
	/// <summary>
	/// Provides facilities to compress SWF files
	/// </summary>
	public static class Compress
	{
		/// <summary>
		/// Compress SWF file. Result is stored using default filename and path.
		/// </summary>
		/// <param name="fileName">
		/// Full path to target file
		/// </param>
		public static void CompressFile (string fileName)
		{
			CompressFile(fileName, fileName.Substring(0, fileName.LastIndexOf('.')) + "_compressed.swf");
		}

		/// <summary>
		/// Compress SWF file. Result is stored using specified path.
		/// </summary>
		/// <param name="targetFileName">Path to target file</param>
		/// <param name="resultFileName">Path to result file</param>
		public static void CompressFile(string targetFileName, string resultFileName)
		{
			Stream fs;

			try
			{
				fs = File.OpenRead(targetFileName);
			}
			catch (FileNotFoundException)
			{
				return;
			}
			var reader = new BinaryReader(fs);

			if (reader.PeekChar() == 0x46)
			{
				byte[] header = reader.ReadBytes(8);
				int len = (int)fs.Length;
				var comp = reader.ReadBytes(len - 8);
				byte[] content = ZlibStream.CompressBuffer(comp);

				var fsTgt = new FileStream(resultFileName, FileMode.Create);
				var writer = new BinaryWriter(fsTgt);
				header[0] = 0x43;
				writer.Write(header);
				writer.Write(content);
				writer.Close();
				writer.Dispose();
			}

			fs.Close();
		}
	}
}
